# coding=utf-8

from core.sqlite3db.SqliteInner import SqliteInner
from core.sqlite3db.SqliteSql import SqliteSql
from tools import convert
from tools.OperationError import OperationError
from tools.httpdoer import Request
from webapp.config import Config


class Vip:
    ID = None
    MOBIL = None
    ECODE = None
    VP_C_VIPTYPE_ENAME = None
    ENAME = None
    CP_C_STORE_ID = None
    AVG_TIME_ACTUAL = None
    CONSUMER_STORE = None
    AMT_ACTUAL = None
    SEX = None
    INTE = None
    OPENDATE = None
    LASTDATE = None
    BIRTHDATE = None

    def query(self, number, storeID):

        try:
            request = Request(Config.ERP_URL + "api/vip/vipelasticsearch")
            request.method = "post"  # 调用 _set_method
            request.timeout = 10  # 调用 _set_timeout
            request.path_params = None
            request.body = {"param": convert.to_json_string({"number": number, "store_id": storeID})}
            r = request.send(json=False)
            print(r.text)
            if r is None:
                raise OperationError(-1, "服务端没有返回数据")
            else:
                self.setInfo(r)
        except BaseException as e:
            print(e)
            # 在线报错是否抛出，由后期设计决定，暂时不抛出
            if type(e) != OperationError:
                raise e

        res = self.querylocal(number,storeID)
        print(res)
        return res

    def setInfo(self, response):

        print(response.text)
        if response.status_code != 200:
            raise OperationError(-1, "服务端请求失败", response.text)

        if response.json == None:
            raise OperationError(-1, "服务器返回格式错误")  # print(type(res))

        res = convert.to_dict(response.json)  # print(type(res))
        if res["code"] == 0:
            message = res["message"]
            print(message)
            r_data = res.get("data", None)
            if r_data is None:
                raise OperationError(-1, "没有激活店仓的记录")
            else:
                # 保存到本地
                print(r_data)
                self.ID = r_data.get("ID")
                self.MOBIL = r_data.get("MOBIL")
                self.ECODE = r_data.get("ECODE")
                self.VP_C_VIPTYPE_ENAME = r_data.get("VP_C_VIPTYPE_ENAME")
                self.ENAME = r_data.get("ENAME")
                self.CP_C_STORE_ID = r_data.get("CP_C_STORE_ID")
                self.AVG_TIME_ACTUAL = r_data.get("AVG_TIME_ACTUAL")
                self.CONSUMER_STORE = r_data.get("CONSUMER_STORE")
                self.AMT_ACTUAL = r_data.get("AMT_ACTUAL")
                self.SEX = r_data.get("SEX")
                self.INTE = r_data.get("INTE")
                self.OPENDATE = r_data.get("OPENDATE")
                self.LASTDATE = r_data.get("LASTDATE")
                self.BIRTHDATE = r_data.get("BIRTHDATE")
                self.save()


    def save(self):
        sqliteinit = SqliteInner()
        sqliteinit.setConnetion("master")
        # sqliteinit.setConnetionWithPath("master", "/Users/zhoucheng/poscloud/core/master.db")
        # # 先尝试创建表
        # sql = SqliteSql.createVipTable
        # cur = sqliteinit.execute(str(sql))
        # print(cur)
        # cur = sqliteinit.execute(str(SqliteSql.createVipIndex))
        # print(cur)
        cur = sqliteinit.execute(str(SqliteSql.insertVip),
                                 (self.ID, self.MOBIL, self.ECODE, self.VP_C_VIPTYPE_ENAME,
                                  self.ENAME, self.CP_C_STORE_ID, self.AVG_TIME_ACTUAL, self.CONSUMER_STORE,
                                  self.AMT_ACTUAL, self.SEX, self.INTE, self.OPENDATE,
                                  self.LASTDATE,self.BIRTHDATE))
        print("save vip：" + str(cur))
        sqliteinit.closedb()


    def querylocal(self, number, storeid):

        sqliteinit = SqliteInner()
        try:
            db = sqliteinit.setConnetion("master")
            # db = sqliteinit.setConnetionWithPath("master","/Users/zhoucheng/poscloud/core/master.db")
            sql = SqliteSql.getVip % (number, number, storeid)
            print(sql)
            list = sqliteinit.execute_list(sql)
            if list != None and len(list) > 0:
                res = list[0]
            else:
                raise OperationError(-1, "数据为空！")
        except Exception as e:
            raise e
        finally:
            sqliteinit.closedb()

        return res


if __name__ == "__main__":
    vip = Vip()
    r = vip.query(13698005414, 206598864955)
    # print(r)
    res = vip.querylocal("13698005414",206598864955)
    # print(res)
